/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.log.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.commons.core.utils.GeneralPropertySourceFactory;
import com.commons.log.dao.SysLogDao;
import com.commons.log.filter.LogFilter;
import com.commons.log.interceptor.LogInterceptor;
import com.commons.log.props.LogProperties;

import jakarta.annotation.PostConstruct;

/**
 * 日志自动配置
 *
 * @author Jasmine
 * @version 1.0
 * @date 2020/12/16 15:58
 * @see SysLogAutoConfiguration
 * @since JDK1.8
 */
@ConditionalOnWebApplication
@AutoConfiguration
@EnableConfigurationProperties(LogProperties.class)
@PropertySource(value = "classpath:default-log.yml", factory = GeneralPropertySourceFactory.class)
public class SysLogAutoConfiguration implements WebMvcConfigurer {

    private static final Logger log = LoggerFactory.getLogger(SysLogAutoConfiguration.class);
    private final LogProperties logProperties;
    private final SysLogDao sysLogDao;

    public SysLogAutoConfiguration(LogProperties logProperties, @Autowired(required = false) SysLogDao sysLogDao) {
        this.logProperties = logProperties;
        this.sysLogDao = sysLogDao;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogInterceptor(sysLogDao, logProperties));
    }

    /**
     * 日志过滤器
     */
    @Bean
    @ConditionalOnMissingBean
    public LogFilter logFilter() {
        return new LogFilter(logProperties);
    }

    @PostConstruct
    public void postConstruct() {
        log.debug("[Commons Starter] - Auto Configuration 'SysLog' completed initialization.");
    }
}